'use strict'

var crypto = require('crypto');
var bodyParser = require('body-parser');
require('body-parser-xml')(bodyParser);
var wxHelper = require('../../common/utils/wxHelper')
var https = require('https')
var config = require('../config')
var restful = require('../../common/utils/restful')
var util = require('../../common/utils/util')

module.exports = function (app) {

    // 解析xml
    app.use(bodyParser.xml({
        limit: '1MB',
        xmlParseOptions: {
            normalize: true,
            normalizeTags: true,
            explicitArray: false
        }
    }));

    var router = app.loopback.Router();
    var mysql = app.dataSources.mysql;
    var wx_mp_account = app.models.wx_mp_account;
    var wx_mp_autoreply = app.models.wx_mp_autoreply;
    var sys_user = app.models.sys_user;
    var rest = {
        code: restful.statusCode.OK,
        msg: 'success',
        error: '',
        data: null,
    }
    var sys_smscode = app.models.sys_smscode;

    // 接入微信服务确认校验
    router.get('/WXMPAuth/:appId', function (req, res) {
        wx_mp_account.find({
            where: {
                app_id: req.params.appId
            }
        }, function (err, models) {
            if (err || models.length <= 0)
                return res.send('access denied!');
            var singleAccountModel = models[0];

            if (singleAccountModel) {
                var currSign, tmp;
                tmp = [singleAccountModel.app_token, req.query.timestamp, req.query.nonce].sort().join("");
                currSign = crypto.createHash("sha1").update(tmp).digest("hex");
                if (currSign == req.query.signature) {
                    return res.send(req.query.echostr);
                }
            }
            return res.end();
        });
    });

    // 微信调用消息服务
    router.post('/WXMPAuth/:appId', function (req, res) {
        wx_mp_account.find({
            where: {
                app_id: req.params.appId
            }
        }, async (err, models) => {
            if (err || models.length <= 0)
                return res.send('access denied!');
            var singleAccountModel = models[0];
            if (singleAccountModel) {
                var api = wxHelper.initApp(singleAccountModel);
                // 获取用户微信输入的消息
                var message = req.body.xml;
                // 根据用户输入的关键词给予用户回复
                // 2018-9-30新规，被动回复news只能为一条
                switch (message.msgtype) {
                    case "text":
                        wxHelper.replyHandler('message', singleAccountModel.app_id, message.fromusername, message.content, api, wx_mp_autoreply);
                        break;
                    case "image":
                        api.sendText(message.fromusername, '欢迎使用公众号，您发送的是图片消息。')
                        break;
                    case "event":
                        console.log(message)
                        if (message.eventkey) {
                            console.log('Handler:' + message.event);
                            wxHelper.replyHandler('event', singleAccountModel.app_id, message.fromusername, message.eventkey, api, wx_mp_autoreply);
                        } else {
                            console.log('Handler:' + message.event);
                            wxHelper.replyHandler('event', singleAccountModel.app_id, message.fromusername, message.event, api, wx_mp_autoreply);
                        }
                        break;
                    default:
                        break;
                }
                // 如从数据库查出的关键词存在多个，则返回选择列表
                res.send();
            }
            return res.end();
        })
    })

    // 微信用户授权
    router.get('/WXMPUser/oauth2/:appId', function (req, res) {
        wx_mp_account.find({
            where: {
                app_id: req.params.appId
            }
        }, async (err, models) => {
            if (err || models.length <= 0)
                return res.send('access denied!');
            var singleAccountModel = models[0];
            if (singleAccountModel) {
                var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code'
                url = url.format(singleAccountModel.app_id, singleAccountModel.app_secret, req.query.code);

                var options = {
                    hostname: 'api.weixin.qq.com',
                    port: 443,
                    path: url,
                    method: 'GET'
                };

                var r = https.request(options, function (res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        //接受数据
                        console.log(chunk)
                    });
                });

                r.on('error', function (e) {
                    console.log('problem with request: ' + e.message);
                });

                r.end();
            } else {
                return res.end();
            }
        })
    })

    // 前端首先检查浏览器，如果是微信浏览器的话，直接调用 wx_login接口，即返回用户数据
    // 根据数据的完整性，判断用户是否已注册，再做注册页面的跳转
    // 非微信浏览器的情况下，无需调用此接口，通过手机号密码，或者短信验证码进行登录
    // 授权的同时即要将微信返回的信息添加进 user 表
    // 直接跳转到 微信授权链接
    router.get('/api/wx_login/:appid', function (req, res) {
        if (!req.params.appid) {
            return res.send({
                res: {
                    code:restful.statusCode.INVALID_REQUEST,
                    msg:'please config the appId!',
                    error:'params failed!',
                    data:null
                }
            });
        }

        if(!req.query.redirect_url)
        {
            return res.send({
                res: {
                    code:restful.statusCode.INVALID_REQUEST,
                    msg:'please config the redirect_url!',
                    error:'params failed!',
                    data:null
                }
            }); 
        }

        wx_mp_account.find({
            where: {
                app_id: req.params.appid
            }
        }, async (err, models) => {
            if (err || models.length <= 0)
                return res.send('access denied!');
            var singleAccountModel = models[0];
            if (singleAccountModel) {
                var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={2}&response_type=code&scope={1}&state=wxauth_code_{0}_{3}&connect_redirect=1#wechat_redirect";
                url = url.format(singleAccountModel.app_id, singleAccountModel.oauth_scope, config.wx_redirect_uri ,req.query.redirect_url);
                res.redirect(url);
            } else {
                return res.end();
            }
        })
    })

    // code 获取授权后，将授权信息返回到前端
    // 记住只返回 openid
    // 用户再根据 openid 创建 accesstoken 并返回
    router.get('/', function (req, res) {
        var params = req.query.state.split('_');
        if (params.length > 0 && params[0] === "wxauth") {
            switch (params[1]) {
                case "code":
                    {
                        wx_mp_account.find({
                            where: {
                                app_id: params[2]
                            }
                        }, async (err, models) => {
                            var singleAccountModel = models[0];
                            if (singleAccountModel) {
                                var _res_front = res;

                                var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code'
                                url = url.format(singleAccountModel.app_id, singleAccountModel.app_secret, req.query.code);

                                var options = {
                                    hostname: 'api.weixin.qq.com',
                                    port: 443,
                                    path: url,
                                    method: 'GET'
                                };

                                var r = await https.request(options, function (res) {
                                    res.setEncoding('utf8');
                                    res.on('data', function (data) {
                                        //接受数据
                                        console.log(data)
                                        data = JSON.parse(data)
                                        sys_user.find({
                                            where: {
                                                and: [{
                                                        wx_openid: data.openid
                                                    },
                                                    {
                                                        app_id: singleAccountModel.app_id
                                                    }
                                                ]
                                            }
                                        }, function (err, results) {
                                            if (err)
                                                return _res_front.send(err);
                                            if (results.length > 0) {
                                                var userData = results[0];

                                                userData.wx_access_token = data.access_token;
                                                userData.wx_access_expires_in = data.expires_in;
                                                userData.wx_refresh_token = data.refresh_token;
                                                userData.save();

                                                //创建 TOKEN 返回
                                                userData.createAccessToken(60 * 60 * 24, function (err, token) {
                                                    rest = {
                                                        code: restful.statusCode.OK,
                                                        msg: 'success',
                                                        error: '',
                                                        data: token
                                                    }
                                                    console.log(rest)
                                                    // 返回用户信息
                                                    var _rdurl = params[3] + '?token=' +  token.id + '&ttl=' + token.ttl + '&userId=' + token.userId + '&created=' + new Date(token.created).getTime()

                                                    _res_front.redirect(_rdurl);

                                                    // return _res_front.send({
                                                    //     res: rest
                                                    // });
                                                })
                                            } else {
                                                // 注册新用户
                                                var userData = new sys_user();
                                                userData.wx_appid = singleAccountModel.app_id
                                                userData.wx_openid = data.openid
                                                userData.wx_access_token = data.access_token
                                                userData.wx_access_expires_in = data.expires_in
                                                userData.wx_refresh_token = data.refresh_token

                                                sys_user.create(userData, function (err, model) {
                                                    if (err) {
                                                        console.log(err)
                                                        return _res_front.send('wx_login create user error!');
                                                    } else {
                                                        //创建 TOKEN 返回
                                                        model.createAccessToken(60 * 60 * 24, function (err, token) {
                                                            rest = {
                                                                code: restful.statusCode.OK,
                                                                msg: 'success',
                                                                error: '',
                                                                data: token
                                                            }
                                                            console.log(rest)
                                                            // 返回用户信息
                                                            var _rdurl = params[3] + '?token=' +  token.id + '&ttl=' + token.ttl + '&userId=' + token.userId + '&created=' +  + new Date(token.created).getTime()

                                                            _res_front.redirect(_rdurl);

                                                            // return _res_front.send({
                                                            //     res: rest
                                                            // });
                                                        })
                                                    }
                                                })
                                            }
                                        })
                                    });
                                });

                                r.on('error', function (e) {
                                    console.log('problem with request: ' + e.message);
                                    return res.send('login to weixin error!')
                                });

                                r.end();
                            } else {
                                return res.send("access denied!");
                            }
                        })
                    }
                    break;
                default:
                    return res.send('no feature!')
            }
        } else {
            return res.send("access denied!");
        }
    })

    // 获取短信验证码
    router.get('/api/get_sms_code', function (req, res) {
        if (!req.query.appid)
            return res.send('access denied!');
        if (!req.query.mobile)
            return res.send('`mobile` is required!');
        if (!req.query.tag)
            return res.send('`tag`  is required!')
        wx_mp_account.find({
            where: {
                app_id: req.query.appid
            }
        }, function (err, mp_account_results) {
            if (err) {
                console.log(err)
                return res.send('access denied!');
            }
            if (mp_account_results.length <= 0) {
                return res.send('app_id is not found , check please!');
            }
            var singleAccountModel = mp_account_results[0];
            var alidysms_config = JSON.parse(singleAccountModel.alidysms_config);

            var tmpCode = alidysms_config[req.query.tag];
            if (!tmpCode)
                return res.send('`tag` is Illegal!')

            sys_smscode.find({
                where: {
                    and: [{
                            app_id: req.query.appid
                        },
                        {
                            mobile: req.query.mobile
                        },
                        {
                            tag:req.query.tag
                        }
                    ]
                },
                order: 'send_date desc'
            }, function (err, smscode_results) {

                var smscodeData = new sys_smscode();
                if(!err && smscode_results.length > 0){
                    smscodeData = smscode_results[0];
                }
                smscodeData.mobile = req.query.mobile;
                smscodeData.app_id = req.query.appid;
                smscodeData.used = false;
                smscodeData.code = ''.random(6, {
                    letters: false
                })
                smscodeData.send_date = new Date();
                smscodeData.tag = req.query.tag;
                smscodeData.save();

                // 根据公众号，配置短信平台的分发，
                util.alidySMS.sendSMS(alidysms_config.AliDy_ACCESS_KEY_ID,
                    alidysms_config.AliDy_ACCESS_KEY_SECRET, alidysms_config.SignName,
                    tmpCode, {
                        code: smscodeData.code
                    }, smscodeData.mobile,
                    function (_sms_res) {
                        return res.send({
                            res: {
                                code: 200,
                                msg: 'success',
                                error: ''
                            }
                        })
                    },
                    function (err) {
                        console.log(err);
                        return res.send({
                            res: {
                                code: 400,
                                msg: 'failed',
                                error: err
                            }
                        })
                    })
            })
        })
    })

    app.use(router);
}